/**
 * 
 */
package com.weirq.mvc.login;

import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.expression.ParseException;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import com.google.protobuf.ServiceException;
import com.weirq.dao.impl.BaseDaoImpl;
import com.weirq.util.DateUtil;

/**
 * @author pc-Haitao
 * @ClassName:RegisterController 邮箱激活验证
 * @Version 版本
 * @Modifiedby 修改人
 * @Copyright 公司名称
 * @date 2016年8月23日下午1:41:36
 */
@Controller
@RequestMapping("/user")
public class RegisterController {
	@RequestMapping(value = "/register", method = { RequestMethod.GET, RequestMethod.POST })
	public ModelAndView load(HttpServletRequest request, HttpServletResponse response) throws ParseException, java.text.ParseException {
		ModelAndView mav = new ModelAndView();// 声明ModelAndView类 对象
		String email = request.getParameter("email");// 获取email
		String validateCode = request.getParameter("validateCode");// 激活码
		try {
			// 调用激活方法
			RegisterController.processActivate(email, validateCode);
			mav.setViewName("activate_success");
		} catch (ServiceException e) {
			request.setAttribute("message", e.getMessage());
			mav.setViewName("activate_failure");
		}
		return mav;
	}

	/**
	 * 处理激活
	 * 
	 * @throws ParseException
	 * @throws java.text.ParseException
	 */
	// /传递激活码和email过来
	public static void processActivate(String email, String validateCode) throws ServiceException, ParseException, java.text.ParseException {
		// 数据访问层，通过email获取用户信息
		BaseDaoImpl baseDaoImpl = new BaseDaoImpl();
		List<Map<String, Object>> li = baseDaoImpl.findbyemail(email);
		// 验证邮箱是否存在
		if (li.get(0).get("email") != null) {
			SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			Date d1 = df.parse(li.get(0).get("registerTime").toString());
			Date d2 = df.parse(DateUtil.DateToString("yyyy-MM-dd HH:mm:ss", new Date()));
			long diff = d2.getTime() - d1.getTime();
			long hours = diff / (1000 * 60 * 60);
			if (hours < 48) {// 判断激活时间是否在48小时之内
				// 验证激活码是否正确
				if (validateCode.equals(li.get(0).get("validateCode").toString())) {
					// 激活成功,并更新用户的激活状态，为已激活
					baseDaoImpl.updateStatus(email, 1);
				} else {
					throw new ServiceException("激活码不正确");
				}
			} else {
				throw new ServiceException("激活链接已过期！" + "<a href=\"http://localhost:8081/CloudDisk/user/register.do?email=" + email + "&validateCode=" + validateCode + "\">请点击此链接重新进行邮箱激活!</a>");
			}
		} else {
			throw new ServiceException("该邮箱未注册（邮箱地址不存在）！");
		}
	}
}
